const { default: mongoose } = require("mongoose");
const fs = require("fs");
const { UPLOAD } = require("../config/config.default");
const { storeImg } = require("./uploadController");

const Img = mongoose.model("Img");

// 上传图片
exports.uploadImg = async (req, res) => {
  let path;
  try {
    const fileDir = UPLOAD.img.dir;
    // 将内存中的Buffer写入磁盘
    const { filePath, fileName } = await storeImg(fileDir)(req);
    path = filePath;
    // 保存到数据库
    const img = new Img(req.body);
    img.user = req.user._id;
    img.path = filePath;

    await img.save();
    res.send(200, {
      message: "上传成功",
      fileName,
      filePath,
    });
  } catch (error) {
    path && fs.rmSync(filePath);
    res.status(400).json({
      error,
    });
  }
};

// 图片详情
exports.getImg = async (req, res) => {
  const imgId = req.params.id;
  const img = await Img.findById(imgId).populate("user", "_id username avatar");
  res.send(200, img);
};
